<template>
<q-page class="bg-dark" ref="pagewrap">

    <div v-if="isLoad" class="absolute-full column items-center justify-center">
        <q-spinner-hourglass color="primary" size="5em"></q-spinner-hourglass>
        <span class="text-grey">页面疯狂加载中……</span>
    </div>

    <div v-if="!isLoad" ref="video-wrap" style="width: 100%">
        <q-responsive :ratio="16 / 9" style="width: 100%">
            <div id="videocontainer" ref="videocontainer" style="width: 100%; height: 100%"></div>
        </q-responsive>
    </div>

    <div v-if="!isLoad" class="column items-stretch no-wrap scroll" :style="downpartstyle">
        <div class="row no-wrap ellipsis">
            <div class="col-grow column q-px-sm q-py-sm ellipsis">
                <div class="q-ml-sm text-subtitle1 text-white ">
                    {{
                            videoData.name.length >= 18
                            ? videoData.name.substring(0, 18) + "…"
                            :videoData.name
                  }}
                </div>
                <div class="q-ml-sm text-grey">{{ videoData.ctime }}</div>
            </div>
            <div class="row items-center justify-center q-mr-md">
                <q-badge outline style="height: 50%; width: 80px" @click="showVersion" color="secondary" class="items-center justify-center">版本{{ version }} <i class="iconfont yf-arrow-down"></i></q-badge>
            </div>
        </div>
        <div class="col-grow">
            <q-tabs v-model="tab" dense class="text-white" active-color="teal-6" indicator-color="teal-6" align="justify" narrow-indicator>
                <q-tab name="comments" :label="'评论(' + comments.length + '条)'" />
                <q-tab name="videoinfo" label="文件信息" />
            </q-tabs>

            <q-separator />

            <q-tab-panels class="bg-grey-10" v-model="tab" animated>
                <q-tab-panel class="q-pa-none column" name="comments">
                    <div class="col-2 row q-pa-sm items-center">
                        <div class="col-8">
                            <q-input v-model="commentsearch" filled dense type="search" color="teal-6" placeholder="搜索评论……" dark clearable @clear="handleclear">
                                <template v-slot:append>
                                    <q-icon @click="searchcom" name="search" />
                                </template>
                            </q-input>
                        </div>
                        <div class="col-4 row items-center justify-evenly">

                            <q-btn round flat @click="handleDownload" color="teal-6" :loading="isComDownload" icon="iconfont yf-download">
                                <q-tooltip anchor="bottom middle" self="top middle" content-class="white">下载评论</q-tooltip>
                            </q-btn>
                            <q-btn round flat color="teal-6" icon="mdi-sort">
                                <!-- <q-tooltip
                          anchor="bottom middle"
                          self="top middle"
                          content-class="white"
                          >排序</q-tooltip
                        > -->
                                <q-menu>
                                    <q-list dense style="min-width: 100px">
                                        <q-item clickable v-close-popup>
                                            <q-item-section @click="handlesort(0)">
                                                <div class="row items-center">最新发布</div>
                                            </q-item-section>
                                        </q-item>
                                        <q-item clickable v-close-popup>
                                            <q-item-section @click="handlesort(1)">
                                                <div class="row items-center">最早发布</div>
                                            </q-item-section>
                                        </q-item>
                                        <q-separator />
                                        <q-item clickable v-close-popup>
                                            <q-item-section @click="handlesort(2)">
                                                <div class="row items-center">按时间码</div>
                                            </q-item-section>
                                        </q-item>
                                    </q-list>
                                </q-menu>
                            </q-btn>
                        </div>
                    </div>

                    <q-card v-for="(item, index) in comments" :key="index" :class="
                      curcomid == item.wc_id
                        ? 'my-card q-pa-sm q-mb-sm transparent activecomment'
                        : 'my-card q-pa-sm q-mb-sm transparent'
                    ">
                        <q-card-section class="q-pa-sm text-white">
                            <div class="text-grey" style="
                          display: flex;
                          align-items: center;
                          flex-wrap: no-wrap;
                        ">
                                <div style="
                            width: 5px;
                            height: 22px;
                            background-color: #409eff;
                            margin-right: 20px;
                          "></div>
                                <div class="ellpsis" @click="handlecomment(item)">
                                    <q-badge outline color="light-blue-5">{{
                            item.curtimelabel
                          }}</q-badge>
                                    <span class="q-ml-sm">{{
                            item.username == null ? item.nickname : item.username
                          }}</span>
                                </div>
                                <div v-if="item.replys.length > 0 " style="position: absolute; right: 5px" class="text-indigo-4">
                                    <q-btn size="sm" @click="isreplyfold = isreplyfold ? false : true" flat>{{
                              isreplyfold
                                ? "展开回复"
                                : "折叠回复"
                            }}</q-btn>
                                </div>
                            </div>
                            <div style="margin-left: 25px" class="q-pt-sm text-body" @click="handlecomment(item)">
                                {{ item.content }}
                            </div>
                        </q-card-section>

                        <q-separator />

                        <q-card-actions class="q-pa-sm text-indigo-4" align="right">
                            <div style="position: absolute; left: 25px; width: 115px" class="text-grey ellipsis" @click="handlecomment(item)">
                                {{ item.com_time }}
                            </div>
                            <div v-if="isLogin">
                                <q-btn v-if="
                                (user.openid && user.openid == item.openid) ||
                                (user.eid && user.eid == item.com_user)
                              " size="sm" @click="handledeletecom(item)" flat>删除</q-btn>
                            </div>

                            <q-btn size="sm" @click="handleclickreply" flat>{{
                          isreply && curcomid == item.wc_id ? "取消回复" : "回复"
                        }}({{ item.replys.length }})</q-btn>
                        </q-card-actions>
                        <q-card-section v-show="curcomid == item.wc_id && isreply" class="q-pa-sm">
                            <q-separator />
                            <q-input clearable dark color="teal-6" counter :maxlength="100" v-model="replycontent" filled autogrow />
                            <q-card-actions class="q-pa-sm text-indigo-4" align="right">
                                <q-btn size="sm" @click="handlereply(item)" flat>发送</q-btn>
                            </q-card-actions>
                        </q-card-section>
                        <q-card v-show="curcomid == item.wc_id && !isreplyfold" v-for="(v, wr_id) in item.replys" :key="wr_id" @click="clickreply(v)" class="q-pl-md transparent">
                            <q-card-section class="q-pa-sm text-white">
                                <div class="text-grey" style="
                            display: flex;
                            align-items: center;
                            flex-wrap: no-wrap;
                          ">
                                    <div style="
                              width: 10px;
                              height: 10px;
                              border-radius: 5px;
                              background-color: #409eff;
                              margin-right: 20px;
                            "></div>
                                    <div class="ellipsis">
                                        {{ v.username == null ? v.nickname : v.username }}
                                        <span class="q-ml-sm">回复</span>

                                        <span class="q-ml-sm">{{
                              v.curusername == null
                                ? v.curnickname
                                : v.curusername
                            }}</span>
                                    </div>
                                </div>
                                <div style="margin-left: 25px" class="q-pt-sm text-body">
                                    {{ v.content }}
                                </div>
                            </q-card-section>

                            <q-separator />

                            <q-card-actions class="q-pa-sm text-indigo-6" align="right">
                                <div style="position: absolute; left: 25px; width: 115px" class="text-grey ellipsis">
                                    {{ v.reply_time }}
                                </div>
                                <q-btn v-if="user && user.eid == v.repuser" size="sm" @click="handledeleterep(v)" flat>删除</q-btn>
                                <q-btn size="sm" @click="handleclickreplyreply" flat>{{
                          curreplyid == v.wr_id && isreplyreply
                            ? "取消回复"
                            : "回复"
                        }}</q-btn>
                            </q-card-actions>
                            <q-card-section v-show="curreplyid == v.wr_id && isreplyreply" class="q-pa-sm">
                                <q-separator />
                                <q-input clearable dark color="teal-6" counter :maxlength="100" v-model="replyreply" filled autogrow />
                                <q-card-actions class="q-pa-sm text-indigo-6" align="right">
                                    <q-btn size="sm" @click="handlereplyreply(v)" flat>发送</q-btn>
                                </q-card-actions>
                            </q-card-section>
                        </q-card>
                    </q-card>

                    <q-dialog v-model="isdeleteDialogshow" persistent>
                        <q-card>
                            <q-card-section class="row items-center">
                                <span class="q-ml-sm">你确认删除这条评论吗？</span>
                            </q-card-section>

                            <q-card-actions align="right">
                                <q-btn flat label="取消" color="primary" @click="canceldelete" />
                                <q-btn flat label="确认删除" color="primary" @click="confirmdelete" />
                            </q-card-actions>
                        </q-card>
                    </q-dialog>
                </q-tab-panel>

                <q-tab-panel name="videoinfo" class="q-pa-none" style="color:white">
                    <q-list padding class="rounded-borders">
                        <q-item-label header class="text-teal-6">基本信息</q-item-label>
                        <q-item v-ripple dense>
                            <q-item-section side class="text-grey-6">
                                <div class="row" style="min-width: 80px; max-width: 100px">
                                    文件名
                                </div>
                            </q-item-section>
                            <q-item-section>
                                {{ videoData.name }}
                            </q-item-section>
                        </q-item>

                        <q-item v-ripple>
                            <q-item-section side class="text-grey-6">
                                <div class="row" style="min-width: 80px; max-width: 100px">
                                    上传者
                                </div>
                            </q-item-section>
                            <q-item-section>
                                {{ videoData.username }}
                            </q-item-section>
                        </q-item>

                        <q-item v-ripple>
                            <q-item-section side class="text-grey-6">
                                <div class="row" style="min-width: 80px; max-width: 100px">
                                    上传时间
                                </div>
                            </q-item-section>
                            <q-item-section>
                                {{ videoData.ctime }}
                            </q-item-section>
                        </q-item>
                        <q-item v-ripple>
                            <q-item-section side class="text-grey-6">
                                <div class="row" style="min-width: 80px; max-width: 100px">
                                    文件大小
                                </div>
                            </q-item-section>
                            <q-item-section>
                                {{ videoinfo.format.size }}
                            </q-item-section>
                        </q-item>
                        <q-item v-ripple>
                            <q-item-section side class="text-grey-6">
                                <div class="row" style="min-width: 80px; max-width: 100px">
                                    分辨率
                                </div>
                            </q-item-section>
                            <q-item-section>
                                {{ videowidth }}x{{ videoheight }}
                            </q-item-section>
                        </q-item>
                        <q-item v-ripple>
                            <q-item-section side class="text-grey-6">
                                <div class="row" style="min-width: 80px; max-width: 100px">
                                    帧率
                                </div>
                            </q-item-section>
                            <q-item-section>
                                {{ videoinfo.streams[0].avg_frame_rate.split("/")[0] }}FPS
                            </q-item-section>
                        </q-item>
                        <q-item v-ripple>
                            <q-item-section side class="text-grey-6">
                                <div class="row" style="min-width: 80px; max-width: 100px">
                                    码率
                                </div>
                            </q-item-section>
                            <q-item-section>
                                {{ videoinfo.format.bit_rate }}
                            </q-item-section>
                        </q-item>
                        <q-item v-ripple>
                            <q-item-section side class="text-grey-6">
                                <div class="row" style="min-width: 80px; max-width: 100px">
                                    格式
                                </div>
                            </q-item-section>
                            <q-item-section>
                                {{ videoformat }}
                            </q-item-section>
                        </q-item>
                        <q-item v-ripple>
                            <q-item-section side class="text-grey-6">
                                <div class="row" style="min-width: 80px; max-width: 100px">
                                    视频编码
                                </div>
                            </q-item-section>
                            <q-item-section>
                                {{ videoinfo.streams[0].codec_name }}
                            </q-item-section>
                        </q-item>
                        <q-item v-ripple>
                            <q-item-section side class="text-grey-6">
                                <div class="row" style="min-width: 80px; max-width: 100px">
                                    音频编码
                                </div>
                            </q-item-section>
                            <q-item-section>
                                {{ videoinfo.streams[1].codec_name }}
                            </q-item-section>
                        </q-item>
                    </q-list>
                </q-tab-panel>
            </q-tab-panels>
        </div>
    </div>

    <q-page-sticky position="bottom-right" :offset="fabPos">
        <q-btn v-if="isfloatbtnshow && !isLoad" rounded color="teal-6" class="z-max  shadow-7 text-primary q-px-md " stack v-touch-pan.prevent.mouse="moveFab" @click="handleclickcom">
            <q-icon size="25px" name="iconfont yf-suggest"></q-icon>
            <div class="text-caption">评论</div>
        </q-btn>
    </q-page-sticky>

    <q-dialog v-model="isComdialog" persistent :maximized="true" transition-show="slide-up" transition-hide="slide-down">
        <q-card class="back-dark text-white">
            <q-bar class="q-my-sm q-pr-none">
                <q-space />
                <q-btn flat icon="close" size="20px" @click="handleclosecom">
                    <q-tooltip content-class="bg-white text-primary">关闭</q-tooltip>
                </q-btn>
            </q-bar>

            <div style="width: 100%">
                <q-responsive :ratio="16 / 9" style="width: 100%">
                    <div :style="markstagestyle" id="my-canvas">
                        <canvas id="canvas" :width="canvaswidth" :height="canvasheight" crossorigin="anonymous"></canvas>
                    </div>
                    <canvas ref="videocanvas" crossorigin="anonymous" id="videocanvas" :style="canvasstyle" :height="canvasheight" :width="canvaswidth"></canvas>
                </q-responsive>
            </div>
            <div class="control row items-center justify-between">
                <div>
                    <q-btn class="q-ml-md q-my-sm" size="22px" push round dense padding="none" color="white" text-color="primary" :icon="
                  isplay ? 'mdi-pause-circle-outline' : 'mdi-play-circle-outline'
                " @click="handleplay"></q-btn>
                    <span class="q-ml-sm">{{ currentTime }}/{{ duration }}</span>
                    <q-btn icon="iconfont yf-textile-products" @click="handlepreview"></q-btn>
                </div>

                <q-btn-dropdown unelevated split menu-anchor="top middle" menu-self="bottom middle" class="q-mr-md" color="back-dark" content-class="white" :label="'倍速' + curspeed">
                    <q-list>
                        <q-item v-if="curspeed !== '2.0'" clickable v-close-popup @click="handlespeed('2.0')">
                            <q-item-section>
                                <q-item-label>2.0</q-item-label>
                            </q-item-section>
                        </q-item>

                        <q-item v-if="curspeed !== '1.5'" clickable v-close-popup @click="handlespeed('1.5')">
                            <q-item-section>
                                <q-item-label>1.5</q-item-label>
                            </q-item-section>
                        </q-item>
                        <q-item v-if="curspeed !== '1.25'" clickable v-close-popup @click="handlespeed('1.25')">
                            <q-item-section>
                                <q-item-label>1.25</q-item-label>
                            </q-item-section>
                        </q-item>
                        <q-item v-if="curspeed !== '1.0'" clickable v-close-popup @click="handlespeed('1.0')">
                            <q-item-section>
                                <q-item-label>1.0</q-item-label>
                            </q-item-section>
                        </q-item>
                        <q-item v-if="curspeed !== '0.75'" clickable v-close-popup @click="handlespeed('0.75')">
                            <q-item-section>
                                <q-item-label>0.75</q-item-label>
                            </q-item-section>
                        </q-item>
                        <q-item v-if="curspeed !== '0.5'" clickable v-close-popup @click="handlespeed('0.5')">
                            <q-item-section>
                                <q-item-label>0.5</q-item-label>
                            </q-item-section>
                        </q-item>
                    </q-list>
                </q-btn-dropdown>
            </div>
            <div style="width: 100%; height: 60px; position: relative" v-show="isshowthumb" class="row items-center justify-center">
                <div style="
                position: absolute;
                z-index: 99999999;
                left: 20px;
                right: 20px;
                height: 60px;
              " class="row items-center justify-center" v-touch-pan.prevent.mouse="handlePan">
                    <div ref="pointer" style="width: 2px; height: 100%; background-color: red"></div>
                </div>
                <div ref="thumbnail" class="thumbnail-wrap" style="overflow: hidden">
                    <img ref="thumbnailBar" :src="thumbnail.src" :style="thumbnailstyle" :height="thumbnail.height" :width="thumbnail.width" alt="" srcset="" />
                </div>
            </div>
            <div v-show="!isSelectCom" class="back-dark card-shadow q-pt-sm">
                <div class="row items-center">
                    <!-- <div >
                        <q-badge outline :style="toolborder" class="q-ma-sm q-pa-xs bg-tm" align="middle">
                            <q-icon name="mdi-cursor-pointer" size="18px" class="q-ml-xs q-mr-xs" @click="drawTypeChange('')" :color="drawType == '' ? color : 'white'">
                                <q-tooltip anchor="top middle" self="bottom middle" content-class="white">选择工具</q-tooltip>
                            </q-icon>

                            <q-icon name="mdi-border-color" size="18px" class="q-ml-xs q-mr-xs" @click="drawTypeChange('pen')" :color="drawType == 'pen' ? color : 'white'">
                                <q-tooltip anchor="top middle" self="bottom middle" content-class="white">画笔工具</q-tooltip>
                            </q-icon>

                            <q-icon name="mdi-rectangle-outline" size="22px" class="q-ml-xs q-mr-xs" :color="drawType == 'rectangle' ? color : 'white'" @click="drawTypeChange('rectangle')">
                                <q-tooltip anchor="top middle" self="bottom middle" content-class="white">矩形工具</q-tooltip>
                            </q-icon>
                            <q-icon name="mdi-arrow-top-right" size="18px" class="q-ml-xs q-mr-xs" @click="drawTypeChange('arrow')" :color="drawType == 'arrow' ? color : 'white'">
                                <q-tooltip anchor="top middle" self="bottom middle" content-class="white">箭头工具</q-tooltip>
                            </q-icon>
                            <q-icon name="mdi-format-text" size="18px" class="q-ml-xs q-mr-xs" @click="drawTypeChange('text')" :color="drawType == 'text' ? color : 'white'">
                                <q-tooltip anchor="top middle" self="bottom middle" content-class="white">文字批注</q-tooltip>
                            </q-icon>
                            <q-icon @click="drawTypeChange('colorselect')" name="mdi-palette" size="18px" class="q-ml-xs q-mr-xs" color="white">
                                <q-tooltip anchor="top middle" self="bottom middle" content-class="white">颜色选择</q-tooltip>
                                <q-popup-proxy ref="colorselect" transition-show="scale" transition-hide="scale">
                                    <q-color @change="handleclosecolor" no-header v-model="color" />
                                </q-popup-proxy>
                            </q-icon>
                            <q-icon name="mdi-undo-variant" size="18px" @click="handlecancel" :color="isEmpty ? 'grey' : 'white'" class="q-ml-xs q-mr-xs">
                                <q-tooltip anchor="top middle" self="bottom middle" content-class="white">撤销</q-tooltip>
                            </q-icon>
                            <q-icon name="mdi-backspace-outline" size="18px" class="q-ml-xs q-mr-xs" @click="hanldeclearcanvas" :color="isEmpty ? 'grey' : 'white'">
                                <q-tooltip anchor="top middle" self="bottom middle" content-class="white">清除画布</q-tooltip>
                            </q-icon>
                        </q-badge>

                    </div> -->

                </div>

                <q-input dark type="textarea" outlined clearable borderless v-model="curcomment.content" class="q-px-sm q-mb-sm q-mt-sm" color="teal-6 bg-grey-10" counter :maxlength="150" placeholder="请输入修改意见……">
                </q-input>
                <div class="q-ml-md row q-pr-md justify-end">
                    <q-badge class="q-ma-sm q-pa-xs bg-tm" align="middle">
                        <q-icon name="mdi-clock-outline" size="22px" class="q-ml-xs q-mr-xs" />
                        <span class="q-mr-xs">{{
            currentTime ? currentTime : "00:00"
          }}</span>
                    </q-badge>
                    <q-btn @click="handlesend" push size="12px" color="cyan-8" label="发送" />
                </div>
            </div>
            <q-card v-if="isSelectCom" class="my-card q-pa-sm q-mb-sm transparent " style="width: 100%">
                <div class="row justify-end">
                    <q-btn outline icon="iconfont yf-suggest" class="q-mr-md q-mb-sm" dense color="teal-6" @click="handleNewCom">新评论</q-btn>
                </div>
                <q-card-section class="q-pa-sm text-white">
                    <div class="text-grey" style="display: flex; align-items: center; flex-wrap: no-wrap">
                        <div style="
                    width: 5px;
                    height: 22px;
                    background-color: #409eff;
                    margin-right: 20px;
                  "></div>
                        <div class="ellpsis">
                            <q-badge outline color="light-blue-5">{{
                    selectedCom.curtimelabel
                  }}</q-badge>
                            <span class="q-ml-sm">{{
                    selectedCom.username == null
                      ? selectedCom.nickname
                      : selectedCom.username
                  }}</span>
                        </div>
                        <div v-if="
                    selectedCom.replys.length > 0 && curcomid == selectedCom.wc_id
                  " style="position: absolute; right: 5px" class="text-indigo-4">
                            <q-btn size="sm" @click="isreplyfold = isreplyfold ? false : true" flat>{{
                      isreplyfold && curcomid == selectedCom.wc_id
                        ? "展开回复"
                        : "折叠回复"
                    }}</q-btn>
                        </div>
                    </div>
                    <div style="margin-left: 25px" class="q-pt-sm text-body">
                        {{ selectedCom.content }}
                    </div>
                </q-card-section>

                <q-separator />

                <q-card-actions class="q-pa-sm text-indigo-4" align="right">
                    <div style="position: absolute; left: 25px; width: 115px" class="text-grey ellipsis">
                        {{ selectedCom.com_time }}
                    </div>
                    <div v-if="user.avatar.length>0">
                        <q-btn v-if="
                        (user.openid && user.openid == selectedCom.openid) ||
                        (user.eid && user.eid == selectedCom.com_user)
                      " size="sm" @click="handledeletecom(selectedCom)" flat>删除</q-btn>
                    </div>

                    <q-btn size="sm" @click="handleclickreply" flat>{{
                  isreply && curcomid == selectedCom.wc_id ? "取消回复" : "回复"
                }}({{ selectedCom.replys.length }})</q-btn>
                </q-card-actions>
                <q-card-section v-show="curcomid == selectedCom.wc_id && isreply" class="q-pa-sm">
                    <q-separator />
                    <q-input clearable dark color="teal-6" counter :maxlength="100" v-model="replycontent" filled autogrow />
                    <q-card-actions class="q-pa-sm text-indigo-4" align="right">
                        <q-btn size="sm" @click="handlereply(selectedCom)" flat>发送</q-btn>
                    </q-card-actions>
                </q-card-section>
                <q-card v-show="curcomid == selectedCom.wc_id && !isreplyfold" v-for="(v, wr_id) in selectedCom.replys" :key="wr_id" @click="clickreply(v)" class="q-pl-md transparent">
                    <q-card-section class="q-pa-sm text-white">
                        <div class="text-grey" style="display: flex; align-items: center; flex-wrap: no-wrap">
                            <div style="
                      width: 10px;
                      height: 10px;
                      border-radius: 5px;
                      background-color: #409eff;
                      margin-right: 20px;
                    "></div>
                            <div class="ellipsis">
                                {{ v.username == null ? v.nickname : v.username }}
                                <span class="q-ml-sm">回复</span>

                                <span class="q-ml-sm">{{
                      v.curusername == null ? v.curnickname : v.curusername
                    }}</span>
                            </div>
                        </div>
                        <div style="margin-left: 25px" class="q-pt-sm text-body">
                            {{ v.content }}
                        </div>
                    </q-card-section>

                    <q-separator />

                    <q-card-actions class="q-pa-sm text-indigo-6" align="right">
                        <div style="position: absolute; left: 25px; width: 115px" class="text-grey ellipsis">
                            {{ v.reply_time }}
                        </div>
                        <q-btn v-if="user && user.eid == v.repuser" size="sm" @click="handledeleterep(v)" flat>删除</q-btn>
                        <q-btn size="sm" @click="handleclickreplyreply" flat>{{
                  curreplyid == v.wr_id && isreplyreply ? "取消回复" : "回复"
                }}</q-btn>
                    </q-card-actions>
                    <q-card-section v-show="curreplyid == v.wr_id && isreplyreply" class="q-pa-sm">
                        <q-separator />
                        <q-input clearable dark color="teal-6" counter :maxlength="100" v-model="replyreply" filled autogrow />
                        <q-card-actions class="q-pa-sm text-indigo-6" align="right">
                            <q-btn size="sm" @click="handlereplyreply(v)" flat>发送</q-btn>
                        </q-card-actions>
                    </q-card-section>
                </q-card>
            </q-card>
        </q-card>
    </q-dialog>
</q-page>
</template>

<script>
import {
    copyToClipboard
} from "quasar";
import storage from "assets/utils/storage";

import {
    getfiledata,
    submitComment,
    getworkComments,
    setworkreply,
    setreplyreply,
    deletecomment,
    downloadComments,
    searchcomment,
    confirmlogin,
    loadfilelist,
} from "assets/api/studio";
import {
    date
} from "quasar";
import {
    getSeconds
} from "assets/utils/stodate";
import "xgplayer";
import HlsJsPlayer from "xgplayer-hls.js";
export default {
    name: "fileindex",
    data() {
        return {
            i: {},
            user: {},
            videoData: {},
            isLogin: false,
            isLoad: true,
            isComdialog: false,
            version: 1,
            versionActions: [],
            downpartstyle: {
                height: "300px",
                width: "100%",
            },
            isFullscreen: false,
            fabPos: [30, 50],
            iscomshow: false,
            qwloginsrc: "",
            loginsrc: "",
            isfloatbtnshow: true,
            login: {
                platform: 0,
                name: "",
                src: "",
            },
            selectedCom: {},
            isSelectCom: false,
            isloginshow: false,
            commentsearch: "",
            sort: 0,
            isreplyfold: true,
            isdeleteDialogshow: false,
            delete_wc_id: "",
            delete_wr_id: "",
            thumbStyle: {
                right: "2px",
                borderRadius: "5px",
                backgroundColor: "#027be3",
                width: "5px",
                opacity: 0.75,
            },
            toolborder: {
                color: "rgb(0, 150, 136)",
            },
            pid: "",
            markstagestyle: {
                position: "absolute",
                zIndex: 2000,
                height: "",
                width: "",
            },
            isComDownload: false,
            isvideoplayershow: true,
            canvaswidth: 0,
            canvasheight: 0,
            offwidth: 0,
            offheight: 0,
            canvasstyle: {
                minWidth: "200px",
                position: "absolute",
                zIndex: 1000,
                // border:'1px solid red'
            },
            tab: "comments",
            poster: "",
            work_id: "",
            player: {},
            isplay: false,
            isplayerReady: false,
            currentTime: "00:00",
            duration: "00:00",
            videowidth: "",
            videoheight: "",

            videoinfo: {
                format: {
                    size: 0,
                    bitRate: "",
                    filename: "",
                },
                streams: [{
                        avg_frame_rate: "",
                        codec_name: "",
                    },
                    {
                        codec_name: "",
                    },
                ],
            },
            videourl: "",
            count: "",
            comments: [],
            curcomid: "",
            replycontent: "",
            isreply: false,
            curreplyid: "",
            replyreply: "",
            isreplyreply: false,
            progress: 0,
            serveurl: "",
            curcomment: {},
            curtime: "",
            ismark: false,
            isshowthumb: true,
            thumbnail: {},
            thumbnailstyle: {
                transform: "translate(0px)",
            },
            imgInfo: {},
            curspeed: "1.0",
            isvoice: true,
            curvolume: 70,
            isadjustvolume: false,
            videoformat: "",

            //mark功能
            rect: [],
            canvas: {},
            showMenu: false,
            x: "",
            y: "",
            mouseFrom: {},
            mouseTo: {},
            drawType: null, //当前绘制图像的种类
            canvasObjectIndex: 0,
            textbox: null,
            rectangleLabel: "warning",
            drawWidth: 2, //笔触宽度
            color: "rgb(0, 150, 136)", //画笔颜色
            drawingObject: null, //当前绘制对象
            moveCount: 1, //绘制移动计数器
            doDrawing: false, // 绘制状态

            //polygon 相关参数
            polygonMode: false,
            pointArray: [],
            lineArray: [],
            activeShape: false,
            activeLine: "",
            line: {},
            delectKlass: {},
            isEmpty: true,
            ismarkready: false,
            isWechat: false,
        };
    },
    beforeCreate() {

        if (this.$platform.inDesktop()) {
            this.$router.replace('/file/' + this.$route.params.work_id);
        }
    },
    created() {
        this.work_id = this.$route.params.work_id
        this.loadfiledata();
        this.loadcomments();
        let userinfo = storage.getItem("userinfo");
        if (userinfo) {
            this.isLogin = true;
            this.user = userinfo;
        }

    },
    mounted() {
        var vm = this;

        window.addEventListener("resize", function () {
            vm.adjustcanvas();
            vm.reloadmarkcanvas();
            vm.getcurheight();
        });

        document.onkeydown = (e) => {
            // 键盘 delect删除所选元素
            if (e.keyCode == 46) {
                this.deleteObj();
            }
            // ctrl+z 删除最近添加的元素
            if (e.keyCode == 90 && e.ctrlKey) {
                this.canvas.remove(
                    this.canvas.getObjects()[this.canvas.getObjects().length - 1]
                );
            }
        };

    },
    watch: {
        drawType() {
            this.canvas.selection = !this.drawType;
        },
        width() {
            this.canvas.setWidth(this.canvaswidth);
        },
        height() {
            this.canvas.setHeight(this.canvasheight);
        },
    },
    updated() {},
    beforeDestroy() {
      window.removeEventListener("resize",function () {
            vm.adjustcanvas();
            vm.reloadmarkcanvas();
            vm.getcurheight();
        });
        if (this.player.isReady) {
            this.player.destroy();
        } else {}
    },
    methods: {
        handleBackToStudio() {
            if (this.isWechat) {

                wx.miniProgram.redirectTo({
                    url: `/pages/project/studio/studio?pid=${this.pid}&tab=video`
                })
            } else {
                this.$router.push('/studio/' + this.pid + "/video?tab=video")

            }

        },
        loadVertion() {
            let serveurl = this.GLOBAL.serveurl;
            let reqdata = {
                pid: this.pid,
            };
            console.log(reqdata);
            let newarr = [];

            loadfilelist(reqdata).then((res) => {
                this.loadPlayer();
                let filelistdata = res.data.data;
                if (filelistdata.length > 0) {
                    filelistdata.forEach((item, index) => {
                        if (item.work_id == this.work_id) {
                            this.version = index + 1;
                        }
                        newarr.push({
                            id: item.work_id,
                            img: serveurl + item.poster,
                            label: "版本号：" +
                                (index + 1) +
                                "  ( " +
                                date.formatDate(item.ctime, "MM-DD HH:mm") +
                                ")",
                            classes: "versionaction",
                        });
                    });
                    this.versionActions = newarr;
                }
            });
        },
        showVersion() {
            let vm = this;
            console.log(this.pid);
            this.$q
                .bottomSheet({
                    dark: true,
                    title: "选择审阅版本",
                    class: "bootomversion",
                    actions: vm.versionActions,
                })
                .onOk((action) => {
                    if (action.id !== vm.work_id) {
                        vm.$router.push("/file/" + action.id);
                    }
                })
                .onCancel(() => {
                    // console.log('Dismissed')
                })
                .onDismiss(() => {
                    // console.log('I am triggered on both OK and Cancel')
                });
        },

        handleAppHome() {
            window.open("https://yfyh.cc");
        },
        //计算评论板块高度
        getcurheight() {
            console.log(this.$refs["pagewrap"].$el);
            console.log(this.$refs["video-wrap"]);
            let pageheight = this.$refs["pagewrap"].$el.clientHeight;

            let videoheight = this.$refs["video-wrap"].clientHeight;
            this.downpartstyle.height = pageheight - videoheight + "px";
            console.log(pageheight, videoheight);
        },
        //浮动操作按钮可拖动
        moveFab(ev) {
            this.draggingFab = ev.isFirst !== true && ev.isFinal !== true;
            this.fabPos = [this.fabPos[0] - ev.delta.x, this.fabPos[1] - ev.delta.y];
        },

        //关闭评论界面
        handleclosecom() {
            this.iscomshow = false;
            this.isSelectCom = false;
            this.isfloatbtnshow = true;
            this.ismarkready = false;
            this.curcomment = {};
            this.isComdialog = false;
            if (this.i) {
                clearInterval(this.i);
            }
            this.hanldeclearcanvas();
        },
        //打开评论界面
        handleclickcom() {
            if (!this.isplayerReady) {
                this.player.start();
            }
            this.isfloatbtnshow = false;

            this.isComdialog = true;
            setTimeout(() => {
                this.player.video.setAttribute('crossorigin', "anonymous")

                this.handleThumbnail();
                this.adjustcanvas();
                this.drawVideo();
                this.handlethumbRoll();
                this.applyTimetoMark();
                setTimeout(() => {
                    let canvas = document.getElementById('videocanvas')
                    canvas.setAttribute('crossorigin', "anonymous")
                    this.loadmarkcanvas();
                }, 300);
            }, 400);
        },

        //从评论查看界面切换新评论
        handleNewCom() {
            this.isSelectCom = false;
            setTimeout(() => {
                this.handleThumbnail();
                this.adjustcanvas();
                this.drawVideo();
                this.handlethumbRoll();
                this.reloadmarkcanvas();
                // setTimeout(() => {
                //   this.loadmarkcanvas();
                // }, 300);
            }, 400);

        },

        handlesort(val) {
            this.sort = val;
            this.loadcomments();
        },
        handleclear() {
            this.comments = [];
            this.loadcomments();
        },
        searchcom() {
            let reqdata = {
                keyword: this.commentsearch,
                work_id: this.work_id,
            };
            searchcomment(reqdata).then((res) => {
                console.log(res.data);
                if (res.data.data.length > 0) {
                    let data = res.data.data;
                    data.forEach((item) => {
                        item.com_time = date.formatDate(item.com_time, "YYYY/MM/DD HH:mm");
                        item.curtimelabel = getSeconds(item.curtime);
                        if (item.replys.length > 0) {
                            item.replys.forEach((v) => {
                                v.reply_time = date.formatDate(
                                    v.reply_time,
                                    "YYYY/MM/DD HH:mm"
                                );
                            });
                        }
                    });
                    this.comments = data;
                } else {
                    this.comments = [];
                    this.$q.notify({
                        color: "red-5",
                        textColor: "white",
                        icon: "warning",
                        position: "top",
                        message: "暂无查询评论！",
                        timeout: 1000,
                    });
                }
            });
        },
        //下载评论
        handleDownload() {
            this.isComDownload = true;
            if (this.user.username) {
                if (this.comments.length > 0) {
                    let reqdata = {
                        work_id: this.work_id,
                        pid: this.pid,
                        comments: this.comments,
                    };
                    downloadComments(reqdata).then((res) => {
                        if (res.data.code == 1) {
                            var save_link = document.createElement("a");
                            save_link.href = this.GLOBAL.serveurl + res.data.dataurl;
                            save_link.download = res.data.filename;
                            this.isComDownload = false;
                            var event = document.createEvent("MouseEvents");
                            event.initMouseEvent(
                                "click",
                                true,
                                false,
                                window,
                                0,
                                0,
                                0,
                                0,
                                0,
                                false,
                                false,
                                false,
                                false,
                                0,
                                null
                            );
                            save_link.dispatchEvent(event);
                        }
                    });
                } else {
                    this.$q.notify({
                        color: "red-5",
                        textColor: "white",
                        icon: "warning",
                        position: "top",
                        message: "暂无评论！",
                        timeout: 1000,
                    });
                }
            } else {
                this.$q.notify({
                    color: "red-5",
                    textColor: "white",
                    icon: "warning",
                    position: "top",
                    message: "请先登录！",
                    timeout: 1000,
                });
            }
        },
        confirmdelete() {
            if (this.delete_wc_id) {
                var reqdata = {
                    wc_id: this.delete_wc_id,
                };
            }
            if (this.delete_wr_id) {
                var reqdata = {
                    wr_id: this.delete_wr_id,
                };
            }
            var vm = this;
            deletecomment(reqdata)
                .then((res) => {
                    if (res.data.code == 1) {
                        vm.$q.notify({
                            position: "center",
                            message: "删除成功！",
                            timeout: 1000,
                            color: "light-green-4",
                            icon: "far fa-check-circle",
                            textColor: "white",
                        });
                        vm.isreply = false;
                        vm.replycontent = "";
                        vm.loadcomments();
                        vm.canceldelete();
                    } else {
                        vm.$q.notify({
                            color: "red-5",
                            textColor: "white",
                            icon: "warning",
                            position: "center",
                            message: "删除失败！",
                            timeout: 1000,
                        });
                    }
                })
                .catch(() => {
                    vm.$q.notify({
                        color: "red-5",
                        textColor: "white",
                        icon: "warning",
                        position: "center",
                        message: "删除失败！",
                        timeout: 1000,
                    });
                });
        },
        canceldelete() {
            this.isdeleteDialogshow = false;
            this.delete_wc_id = "";
            this.delete_wr_id = "";
        },
        handleclickreply() {
            if (this.user.username) {
                if (this.isreply) {
                    this.isreply = false;
                } else {
                    this.isreply = true;
                }
            } else {
                this.$q.notify({
                    color: "red-5",
                    textColor: "white",
                    icon: "warning",
                    position: "center",
                    message: "请先登录！",
                    timeout: 1000,
                });
            }
        },
        handleclickreplyreply() {
            if (this.user.username) {
                if (this.isreplyreply) {
                    this.isreplyreply = false;
                } else {
                    this.isreplyreply = true;
                }
            } else {
                this.$q.notify({
                    color: "red-5",
                    textColor: "white",
                    icon: "warning",
                    position: "center",
                    message: "请先登录！",
                    timeout: 1000,
                });
            }
        },
        clickreply(e) {
            this.curreplyid = e.wr_id;
        },
        handledeletecom(e) {
            this.isdeleteDialogshow = true;
            this.delete_wc_id = e.wc_id;
        },
        handledeleterep(e) {
            this.isdeleteDialogshow = true;
            this.delete_wr_id = e.wr_id;
        },
        //回复
        handlereply(e) {
            if (!this.replycontent) {
                return;
            }
            if (this.user.eid) {
                if (e.eid) {
                    var reqdata = {
                        repuser: this.user.eid,
                        curuser: e.eid,
                        content: this.replycontent,
                        wc_id: e.wc_id,
                    };
                } else {
                    var reqdata = {
                        repuser: this.user.eid,
                        curopenid: e.openid,
                        content: this.replycontent,
                        wc_id: e.wc_id,
                    };
                }
            } else {
                if (e.eid) {
                    var reqdata = {
                        repopenid: this.user.openid,
                        curuser: e.eid,
                        content: this.replycontent,
                        wc_id: e.wc_id,
                    };
                } else {
                    var reqdata = {
                        repopenid: this.user.openid,
                        curopenid: e.openid,
                        content: this.replycontent,
                        wc_id: e.wc_id,
                    };
                }
            }

            var vm = this;
            setworkreply(reqdata)
                .then((res) => {
                    if (res.data.code == 1) {
                        vm.$q.notify({
                            position: "center",
                            message: "回复成功！",
                            timeout: 1000,
                            color: "light-green-4",
                            icon: "far fa-check-circle",
                            textColor: "white",
                        });
                        vm.isreply = false;
                        vm.replycontent = "";
                        vm.loadcomments();
                    } else {
                        vm.$q.notify({
                            color: "red-5",
                            textColor: "white",
                            icon: "warning",
                            position: "center",
                            message: "回复失败！",
                            timeout: 1000,
                        });
                    }
                })
                .catch(() => {
                    vm.$q.notify({
                        color: "red-5",
                        textColor: "white",
                        icon: "warning",
                        position: "center",
                        message: "回复失败！",
                        timeout: 1000,
                    });
                });
        },
        handlereplyreply(e) {
            if (!this.replyreply) {
                return;
            }
            let reqdata = {
                repuser: this.user.eid,
                curuser: e.repuser,
                content: this.replyreply,
                wc_id: e.wc_id,
            };
            var vm = this;
            setreplyreply(reqdata)
                .then((res) => {
                    if (res.data.code == 1) {
                        vm.$q.notify({
                            position: "center",
                            message: "回复成功！",
                            timeout: 1000,
                            color: "light-green-4",
                            icon: "far fa-check-circle",
                            textColor: "white",
                        });
                        vm.isreplyreply = false;
                        vm.replyreply = "";
                        vm.loadcomments();
                    } else {
                        vm.$q.notify({
                            color: "red-5",
                            textColor: "white",
                            icon: "warning",
                            position: "center",
                            message: "回复失败！",
                            timeout: 1000,
                        });
                    }
                })
                .catch(() => {
                    vm.$q.notify({
                        color: "red-5",
                        textColor: "white",
                        icon: "warning",
                        position: "center",
                        message: "回复失败！",
                        timeout: 1000,
                    });
                });
        },
        //点击评论
        handlecomment(e) {
            if (!this.isplayerReady) {
                this.player.start();
            }
            this.isSelectCom = true;
            this.curcomid = e.wc_id;
            let seektime = e.curtime;
            this.selectedCom = e;
            if (e.markimg) {
                this.reloadmarkcanvas();
                this.isfloatbtnshow = false;
                this.isComdialog = true;
                setTimeout(() => {
                    this.handleThumbnail();
                    this.adjustcanvas();
                    this.drawVideo();
                    this.handlethumbRoll();
                    setTimeout(() => {
                        this.player.pause();
                        this.player.currentTime = seektime;
                        this.loadmarkcanvas();
                        setTimeout(() => {
                            let markimg = this.GLOBAL.serveurl + e.markimg;
                            var vm = this;
                            var imgInstance = new fabric.Image.fromURL(markimg, function (
                                oImg
                            ) {
                                oImg.scaleToHeight(vm.canvasheight, false);
                                oImg.scaleToWidth(vm.canvaswidth, false);
                                vm.canvas.add(oImg);
                            }, {
                                crossOrigin: "anonymous"
                            });
                        });
                    }, 300);
                }, 400);
            } else {
                this.isfloatbtnshow = false;
                this.isComdialog = true;
                setTimeout(() => {
                    this.handleThumbnail();
                    this.adjustcanvas();
                    this.drawVideo();
                    this.handlethumbRoll();
                    setTimeout(() => {
                        this.player.pause();
                        this.player.currentTime = seektime;
                        this.loadmarkcanvas();
                    }, 300);
                }, 400);
            }
        },
        //加载评论
        loadcomments() {
            this.comments = [];
            let reqdata = {
                work_id: this.work_id,
                sort: this.sort,
            };
            getworkComments(reqdata).then((res) => {
                if (res.data.data.length > 0) {
                    let data = res.data.data;
                    data.forEach((item) => {
                        item.com_time = date.formatDate(item.com_time, "YYYY/MM/DD HH:mm");
                        item.curtimelabel = getSeconds(item.curtime);
                        if (item.replys.length > 0) {
                            item.replys.forEach((v) => {
                                v.reply_time = date.formatDate(
                                    v.reply_time,
                                    "YYYY/MM/DD HH:mm"
                                );
                            });
                        }
                        if (this.selectedCom.wc_id && this.selectedCom.wc_id == item.wc_id) {
                            this.selectedCom = item
                        }
                    });
                    this.comments = data;
                }
            });
        },
        //撤销操作
        handlecancel() {
            this.canvas.remove(
                this.canvas.getObjects()[this.canvas.getObjects().length - 1]
            );
        },
        //颜色选择成功后触发
        handleclosecolor() {
            this.toolborder.color = this.color;
            this.$refs["colorselect"].hide();
            this.drawType = "";
        },
        //将播放器时间赋予当前批注时间
        applyTimetoMark() {
            this.curcomment.curtime = this.player.currentTime;
        },
        //重载画布
        reloadmarkcanvas() {
            if (this.ismarkready) {
                console.log(1);
                var arr = document.getElementsByClassName("canvas-container");
                for (let i = 0; i < arr.length; i++) {
                    if (arr[i] != null) arr[i].parentNode.removeChild(arr[i]);
                }
                var canvas = document.createElement("canvas");
                canvas.id = "canvas";
                canvas.crossorigin = "anonymous";
                canvas.width = this.canvaswidth;
                canvas.height = this.canvasheight;
                document.getElementById("my-canvas").appendChild(canvas);
                this.loadmarkcanvas();
            }
        },
        //加载评论批注画布
        loadmarkcanvas() {
            this.canvas = new fabric.Canvas("canvas", {
                // skipTargetFind: false, //当为真时，跳过目标检测。目标检测将返回始终未定义。点击选择将无效
                // selectable: false,  //为false时，不能选择对象进行修改
                // selection: false   // 是否可以多个对象为一组
            });
            this.canvas.selectionColor = "rgba(0,0,0,0.05)";
            this.canvas.on("mouse:down", this.mousedown);
            this.canvas.on("mouse:move", this.mousemove);
            this.canvas.on("mouse:up", this.mouseup);
            this.canvas.on("object:added", this.isCanvasEmpty);
            this.canvas.on("object:removed", this.isCanvasEmpty);
            this.ismarkready = true;
        },

        //检测画布是否为空
        isCanvasEmpty() {
            if (this.canvas.isEmpty()) {
                this.isEmpty = true;
            } else {
                this.isEmpty = false;
            }
        },
        // 开始绘制时，指定绘画种类
        drawTypeChange(e) {
            this.drawType = e;
            this.canvas.skipTargetFind = !!e;
            if (e == "pen") {
                // isDrawingMode为true 才可以自由绘画
                this.canvas.isDrawingMode = true;
                this.canvas.freeDrawingBrush.color = this.color;
                this.canvas.freeDrawingBrush.width = 3;
            } else {
                this.canvas.isDrawingMode = false;
                if (e !== "text" && this.textbox) {
                    this.textbox.exitEditing();
                }
            }
        },
        // 鼠标按下时触发
        mousedown(e) {
            // 记录鼠标按下时的坐标
            var xy = e.pointer || this.transformMouse(e.e.offsetX, e.e.offsetY);
            this.mouseFrom.x = xy.x;
            this.mouseFrom.y = xy.y;
            this.doDrawing = true;
            if (this.drawType == "text") {
                this.drawing();
            }
            // 绘制多边形
            if (this.drawType == "polygon") {
                this.canvas.skipTargetFind = false;
                try {
                    // 此段为判断是否闭合多边形，点击红点时闭合多边形
                    if (this.pointArray.length > 1) {
                        // e.target.id == this.pointArray[0].id 表示点击了初始红点
                        if (e.target && e.target.id == this.pointArray[0].id) {
                            this.generatePolygon();
                        }
                    }
                    //未点击红点则继续作画
                    if (this.polygonMode) {
                        this.addPoint(e);
                    }
                } catch (error) {}
            }
        },
        // 鼠标松开执行
        mouseup(e) {
            var xy = e.pointer || this.transformMouse(e.e.offsetX, e.e.offsetY);
            this.mouseTo.x = xy.x;
            this.mouseTo.y = xy.y;
            this.drawingObject = null;
            this.moveCount = 1;
            if (this.drawType != "polygon") {
                this.doDrawing = false;
            }
        },

        //鼠标移动过程中已经完成了绘制
        mousemove(e) {
            if (this.moveCount % 2 && !this.doDrawing) {
                //减少绘制频率
                return;
            }
            this.moveCount++;
            var xy = e.pointer || this.transformMouse(e.e.offsetX, e.e.offsetY);
            this.mouseTo.x = xy.x;
            this.mouseTo.y = xy.y;
            // 多边形与文字框特殊处理
            if (this.drawType != "text" || this.drawType != "polygon") {
                this.drawing(e);
            }
            if (this.drawType == "polygon") {
                if (this.activeLine && this.activeLine.class == "line") {
                    var pointer = this.canvas.getPointer(e.e);
                    this.activeLine.set({
                        x2: pointer.x,
                        y2: pointer.y
                    });

                    var points = this.activeShape.get("points");
                    points[this.pointArray.length] = {
                        x: pointer.x,
                        y: pointer.y,
                        zIndex: 1,
                    };
                    this.activeShape.set({
                        points: points,
                    });
                    this.canvas.renderAll();
                }
                this.canvas.renderAll();
            }
        },
        deleteObj() {
            this.canvas.getActiveObjects().map((item) => {
                this.canvas.remove(item);
            });
        },
        transformMouse(mouseX, mouseY) {
            return {
                x: mouseX / 1,
                y: mouseY / 1
            };
        },

        drawing(e) {
            if (this.drawingObject) {
                this.canvas.remove(this.drawingObject);
            }
            var canvasObject = null;
            var left = this.mouseFrom.x,
                top = this.mouseFrom.y,
                mouseFrom = this.mouseFrom,
                mouseTo = this.mouseTo;
            switch (this.drawType) {
                case "arrow": //箭头
                    var x1 = mouseFrom.x,
                        x2 = mouseTo.x,
                        y1 = mouseFrom.y,
                        y2 = mouseTo.y;
                    var w = x2 - x1,
                        h = y2 - y1,
                        sh = Math.cos(Math.PI / 4) * 16;
                    var sin = h / Math.sqrt(Math.pow(w, 2) + Math.pow(h, 2));
                    var cos = w / Math.sqrt(Math.pow(w, 2) + Math.pow(h, 2));
                    var w1 = (16 * sin) / 4,
                        h1 = (16 * cos) / 4,
                        centerx = sh * cos,
                        centery = sh * sin;
                    /**
                     * centerx,centery 表示起始点，终点连线与箭头尖端等边三角形交点相对x，y
                     * w1 ，h1用于确定四个点
                     */

                    var path = " M " + x1 + " " + y1;
                    path += " L " + (x2 - centerx + w1) + " " + (y2 - centery - h1);
                    path +=
                        " L " + (x2 - centerx + w1 * 2) + " " + (y2 - centery - h1 * 2);
                    path += " L " + x2 + " " + y2;
                    path +=
                        " L " + (x2 - centerx - w1 * 2) + " " + (y2 - centery + h1 * 2);
                    path += " L " + (x2 - centerx - w1) + " " + (y2 - centery + h1);
                    path += " Z";
                    canvasObject = new fabric.Path(path, {
                        stroke: this.color,
                        fill: this.color,
                        strokeWidth: this.drawWidth,
                    });
                    break;
                case "ellipse": //椭圆
                    // 按shift时画正圆，只有在鼠标移动时才执行这个，所以按了shift但是没有拖动鼠标将不会画圆
                    if (e.e.shiftKey) {
                        mouseTo.x - left > mouseTo.y - top ?
                            (mouseTo.y = top + mouseTo.x - left) :
                            (mouseTo.x = left + mouseTo.y - top);
                    }
                    var radius =
                        Math.sqrt(
                            (mouseTo.x - left) * (mouseTo.x - left) +
                            (mouseTo.y - top) * (mouseTo.y - top)
                        ) / 2;
                    canvasObject = new fabric.Ellipse({
                        left: (mouseTo.x - left) / 2 + left,
                        top: (mouseTo.y - top) / 2 + top,
                        stroke: this.color,
                        fill: "rgba(255, 255, 255, 0)",
                        originX: "center",
                        originY: "center",
                        rx: Math.abs(left - mouseTo.x) / 2,
                        ry: Math.abs(top - mouseTo.y) / 2,
                        strokeWidth: this.drawWidth,
                    });
                    break;
                case "rectangle": //长方形
                    // 按shift时画正方型
                    if (e.e.shiftKey) {
                        mouseTo.x - left > mouseTo.y - top ?
                            (mouseTo.y = top + mouseTo.x - left) :
                            (mouseTo.x = left + mouseTo.y - top);
                    }
                    var path =
                        "M " +
                        mouseFrom.x +
                        " " +
                        mouseFrom.y +
                        " L " +
                        mouseTo.x +
                        " " +
                        mouseFrom.y +
                        " L " +
                        mouseTo.x +
                        " " +
                        mouseTo.y +
                        " L " +
                        mouseFrom.x +
                        " " +
                        mouseTo.y +
                        " L " +
                        mouseFrom.x +
                        " " +
                        mouseFrom.y +
                        " z";
                    canvasObject = new fabric.Path(path, {
                        left: left,
                        top: top,
                        stroke: this.color,
                        strokeWidth: this.drawWidth,
                        fill: "rgba(255, 255, 255, 0)",
                        hasControls: false,
                    });
                    //也可以使用fabric.Rect
                    break;
                case "text": //文本框
                    this.textbox = new fabric.Textbox("", {
                        left: mouseFrom.x,
                        top: mouseFrom.y - 10,
                        // width: 150,
                        fontSize: 18,
                        borderColor: this.color,
                        fill: this.color,
                        hasControls: true,
                    });
                    this.canvas.add(this.textbox);
                    this.textbox.enterEditing();
                    // this.textbox.hiddenTextarea.focus();
                    break;

                default:
                    break;
            }

            if (canvasObject) {
                // canvasObject.index = getCanvasObjectIndex();\
                this.canvas.add(canvasObject); //.setActiveObject(canvasObject)
                this.drawingObject = canvasObject;
            }
        },
        //清空画布
        hanldeclearcanvas() {
            this.canvas.clear();
            this.isCanvasEmpty();
            this.drawType = null;
        },

        //调整视频音量
        handlevolume(value) {
            this.player.volume(value / 100);
            this.isadjustvolume = false;
            if (value == 0) {
                this.isvoice = false;
            } else {
                this.isvoice = true;
            }
        },
        //调整视频速度
        handlespeed(speed) {
            this.curspeed = speed;
            console.log(speed);
            console.log(this.player.switchPlaybackRate);
            this.player.switchPlaybackRate(speed);
        },

        //调整画布
        adjustcanvas() {
            let videocontainer = document.getElementById("videocanvas");
            let curwidth = videocontainer.clientWidth;
            let curheight = videocontainer.clientHeight;
            if (this.canvasheight <= curheight) {
                this.canvaswidth = curwidth;
                this.canvasheight = (curwidth / this.videowidth) * this.videoheight;
                this.canvasstyle.top = this.markstagestyle.top =
                    (curheight - this.canvasheight) / 2 + "px";
                this.canvasstyle.left = this.markstagestyle.left = 0;

                this.markstagestyle.width = this.canvaswidth + "px";
                this.markstagestyle.height = this.canvasheight + "px";
            }
            if (this.canvasheight > curheight) {
                this.canvasheight = curheight;
                this.canvaswidth = (curheight / this.videoheight) * this.videowidth;
                this.canvasstyle.top = this.markstagestyle.top = 0;
                this.canvasstyle.left = this.markstagestyle.left =
                    (curwidth - this.canvaswidth) / 2 + "px";
                this.markstagestyle.width = this.canvaswidth + "px";
                this.markstagestyle.height = this.canvasheight + "px";
            }
        },
        //滑动缩略图进度条
        handlePan(e) {
            // console.log(e);

            let curwidth = parseInt(
                this.thumbnailstyle.transform
                .replace("translate(", "")
                .replace("px)", "")
            );
            let imgwidth = this.$refs.thumbnailBar.clientWidth;
            let offset = e.offset.x;
            let transwidth = curwidth + offset / 50;
            let pointer = this.$refs.pointer;
            let initwidth = pointer.offsetLeft + 20;

            let curPercent = ((initwidth - curwidth) / imgwidth).toFixed(6);
            var percent = 0;
            if (curPercent >= 0 || curPercent <= 1) {
                percent = curPercent;
            } else if (curPercent < 0) {
                percent = 0;
            } else if (curPercent > 1) {
                percent = 1;
            }

            if (curwidth < -(imgwidth - initwidth)) {
                this.thumbnailstyle.transform =
                    "translate(" + -(imgwidth - initwidth) + "px)";
            } else if (curwidth > initwidth) {
                this.thumbnailstyle.transform = "translate(" + initwidth + "px)";
            } else {
                this.thumbnailstyle.transform = "translate(" + transwidth + "px)";
                this.player.currentTime = this.player.duration * percent;
                this.drawVideo();
            }
        },
        handlepreview(evt) {
            this.isshowthumb = true;

            setTimeout(() => {
                console.log(this.$refs.thumbnail);
                let width = this.$refs["thumbnail"].clientWidth;
                if (this.$refs["thumbnail"]) {
                    var thumbheight = this.$refs["thumbnail"].clientHeight;
                }
            }, 200);
            // let layerwidth = evt.layerX;
        },
        handleThumbnail() {
            let pointer = this.$refs.pointer;
            console.log(pointer.offsetLeft);
            let initwidth = pointer.offsetLeft + 20;
            // let curprogress = layerwidth / width;
            this.thumbnailstyle.transform = "translate(" + initwidth + "px)";
        },
        //缩略图模拟进度条滚动
        handlethumbRoll() {
            if (this.isComdialog) {
                let curPercent = this.player.currentTime / this.player.duration;
                let imgwidth = this.$refs.thumbnailBar.clientWidth;
                let pointer = this.$refs.pointer;
                let initwidth = pointer.offsetLeft + 20;
                let curwidth = initwidth - imgwidth * curPercent;
                this.thumbnailstyle.transform = "translate(" + curwidth + "px)";
            }
        },
        //绘制视频
        drawVideo() {
            if (this.isComdialog) {
                var vm = this;
                let canvas = document.getElementById("videocanvas");
                let video = this.$refs.videocontainer.children[0];
                var context = canvas.getContext("2d");
                context.imageSmoothingEnabled = false;
                this.i = setInterval(function () {
                    context.drawImage(video, 0, 0, vm.canvaswidth, vm.canvasheight);
                }, 20);
            }
        },
        handleplay() {
            if (this.isplay) {
                this.player.pause();
            } else {
                this.player.play();
            }
        },
        generateImg() {
            let img = new Image();
            console.log("生成图片");
            img.src = this.serveurl + this.videoData.thumbnail;
            const vm = this;
            img.onload = function () {
                vm.$set(vm.imgInfo, "width", img.width);
                vm.$set(vm.imgInfo, "height", img.height);
            };

            this.thumbnail.src = this.serveurl + this.videoData.thumbnail;
            this.thumbnail.height = 40;
            this.thumbnail.width = (this.imgInfo.widtht * 40) / this.imgInfo.height;
        },
        onPlayerReady() {
            this.generateImg();
        },

        onScreenShotBtnClick() {
            let img = this.img
            img.onload = (function () {
                this.canvasCtx.drawImage(this.player.video, 0, 0, canvas.width, canvas.height)
                img.setAttribute('crossOrigin', 'anonymous')
                img.src = canvas.toDataURL('image/png').replace('image/png', 'image/octet-stream')
                // let screenShotImg = img.src.replace(/^data:image\/[^;]+/, 'data:application/octet-stream')
                // saveScreenShot(screenShotImg, '截图.png')
            })()
        },
        screenShot() {
            let canvas = document.createElement('canvas');
            this.canvasCtx = canvas.getContext('2d')
            this.img = new Image();
            canvas.width = this.canvaswidth
            canvas.height = this.canvasheight

        },
        handleSubmit() {
            let comment = this.curcomment;
            var vm = this;
            submitComment(comment)
                .then((res) => {
                    if (res.data.code == 1) {
                        vm.$q.notify({
                            position: "center",
                            message: "评论成功！",
                            timeout: 1000,
                            color: "light-green-4",
                            icon: "far fa-check-circle",
                            textColor: "white",
                        });
                        vm.loadcomments();
                        vm.hanldeclearcanvas();
                        vm.curcomment = {};
                    } else {
                        vm.$q.notify({
                            color: "red-5",
                            textColor: "white",
                            icon: "warning",
                            position: "center",
                            message: "评论失败！",
                            timeout: 1000,
                        });
                    }
                })
                .catch((err) => {
                    vm.$q.notify({
                        color: "red-5",
                        textColor: "white",
                        icon: "warning",
                        position: "center",
                        message: "评论失败！",
                        timeout: 1000,
                    });
                });
        },

        //提交评论
        handlesend() {
            if (this.user.username) {
                if (!this.curcomment.content && this.isEmpty) {
                    this.$q.notify({
                        position: "center",
                        message: "请先写下你的建议吧！",
                        timeout: 1000,
                    });
                    return;
                } else {

                    this.curcomment.pid = this.pid;
                    this.curcomment.work_id = this.work_id;
                    if (this.user.eid) {
                        this.curcomment.eid = this.user.eid;
                    } else {
                        this.curcomment.openid = this.user.openid;
                    }
                    this.curcomment.videourl = this.videourl;

                    this.curcomment.commentimg = '';
                    this.curcomment.curcanvaswidth = this.canvaswidth;
                    this.curcomment.curcanvasheight = this.canvasheight;
                    this.handleSubmit();

                }
            } else {
                this.$q.notify({
                    color: "red-5",
                    textColor: "white",
                    icon: "warning",
                    position: "top",
                    message: "请先登录！",
                    timeout: 1000,
                });
            }
        },
        saveFile(data, filename) {
            var save_link = document.createElement("a");
            save_link.href = data;
            save_link.download = filename;

            var event = document.createEvent("MouseEvents");
            event.initMouseEvent(
                "click",
                true,
                false,
                window,
                0,
                0,
                0,
                0,
                0,
                false,
                false,
                false,
                false,
                0,
                null
            );
            save_link.dispatchEvent(event);
        },

        loadPlayer() {
            this.serveurl = this.GLOBAL.serveurl;
            this.videourl = this.serveurl + this.videoData.m3u8url;
            this.poster = this.serveurl + this.videoData.poster;

            var vm = this;
            this.player = new HlsJsPlayer({
                id: "videocontainer",
                url: this.videourl,
                fluid: true,
                lang: 'zh-cn',
                poster: this.poster,
                playbackRate: [0.5, 0.75, 1, 1.5, 2],
                defaultPlaybackRate: 1,
                keyShortcut: "on",
                controls: true,
                "x5-video-player-type": "h5",
                playsinline: false,

            });
            var vm = this;
            this.player.on("ready", () => {

                vm.onPlayerReady();
                vm.getcurheight();
            });
            this.player.on("play", function () {
                vm.isplay = true;
                if (
                    vm.isComdialog
                ) {
                    vm.applyTimetoMark();
                    vm.drawVideo();
                }

            });
            this.player.on("timeupdate", function () {
                if (vm.isComdialog) {
                    vm.handlethumbRoll();
                    vm.drawVideo();
                    vm.applyTimetoMark();
                }

                vm.currentTime = getSeconds(vm.player.currentTime);
            });
            this.player.on("pause", function () {
                vm.isplay = false;
                if (vm.isComdialog) {
                    vm.applyTimetoMark();
                    clearInterval(vm.i);
                }

            });
            this.player.on("complete", function () {
                vm.isplayerReady = true;
            });
        },

        loadfiledata() {
            let reqdata = {
                work_id: this.work_id,
            };
            getfiledata(reqdata)
                .then((res) => {
                    this.isLoad = false;
                    let filedata = res.data.data;
                    let videoData = filedata[0][0];
                    this.pid = videoData.pid;
                    this.$emit('update:status', videoData.status)
                    let ctime = date.formatDate(videoData.ctime, "YYMMDD");
                    if (!videoData.name) {
                        videoData.name = ctime + "-" + videoData.pname;
                    }
                    videoData.ctime = date.formatDate(
                        videoData.ctime,
                        "YYYY-MM-DD HH:mm"
                    );
                    videoData.videoinfo = JSON.parse(videoData.videoinfo);
                    let duration = videoData.videoinfo.format.duration;
                    let bitrate = videoData.videoinfo.format.bit_rate;
                    let newbitrate =
                        Math.floor((bitrate / 1024 / 1024) * 100) / 100 + "mbps";
                    let size = videoData.videoinfo.format.size;
                    let newsize = Math.floor((size / 1024 / 1024) * 100) / 100 + "MB";
                    let newduration = getSeconds(duration);
                    videoData.videoinfo.format.duration = newduration;
                    videoData.videoinfo.format.bit_rate = newbitrate;
                    videoData.videoinfo.format.size = newsize;
                    document.title = videoData.name + "--视频审阅";
                    let arr = videoData.videoinfo.format.filename.split(".");
                    this.videoformat = arr[arr.length - 1];
                    this.videoData = videoData;
                    this.$emit('update', videoData)
                    this.videoinfo = videoData.videoinfo;
                    this.duration = this.videoinfo.format.duration;
                    this.videowidth = videoData.videoinfo.streams[0].width;
                    this.videoheight = videoData.videoinfo.streams[0].height;
                    return;
                }).then(() => {
                    this.loadVertion();
                })

        },
    },
};
</script>

<style lang="scss">
.markwrap {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 100%;
}

.card-shadow {
    box-shadow: 2px 2px 10px rgb(118 173 130 / 20%);
}

>input input::-webkit-input-placeholder {
    color: #cccccc;
}

.thumbnail-wrap {
    z-index: 100000;
    height: 40px;
    width: 100%;
    color: red;
    border: 1px solid grey;
}

.videobg {
    background-color: rgb(0, 0, 0);
}

.activecomment {
    color: white;
    border: 1px solid rgb(0, 150, 136);
    border-radius: 3px;
}

.bootomversion {
    background-color: rgb(0, 0, 0);
    min-height: 300px;
}

.versionaction {
    height: 60px;
}

.versionaction img {
    height: 54px;
    width: 96px;
    border-radius: 5px;
}
</style>
